package com.sgb.trip.view.activity;

import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.RequiresApi;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.MainEvent;
import com.sgb.link.entity.PickSelectEntity;
import com.sgb.link.entity.trip.AirportCityEntity;
import com.sgb.link.entity.trip.FlightSearchEntity;
import com.sgb.link.router.PathTrip;
import com.sgb.link.view.widget.IpPopWindow;
import com.sgb.trip.R;
import com.sgb.trip.databinding.TripActivityChooseSingleFlightBinding;
import com.sgb.trip.entity.FlightInfoEntity;
import com.sgb.trip.entity.FlightLineSearchEntity;
import com.sgb.trip.view.adapter.FlightInfoAdapter;
import com.sgb.trip.view.widget.FlightMoreFilterPopWindow;
import com.sgb.trip.view.widget.FlightPopWindow;
import com.sgb.trip.viewmodel.FlightSearchViewModel;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickerHelper;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Describe:    单程选择航班
 * Author:  黄淋
 * Date:    2021/9/10
 */
@Route(path = PathTrip.FlightSearchActivity)
public class FlightSearchActivity extends BaseActivity<FlightSearchViewModel, TripActivityChooseSingleFlightBinding> {

    private FlightSearchViewModel mViewModel;

    private FlightInfoAdapter mAdapter;
    private FlightPopWindow flightPopWindow;
    private FlightMoreFilterPopWindow moreWindow;//更多筛选

    private IpPopWindow peopleCountWindow;//乘客人数筛选
    TimePickerView mTimePickerSrart;
    TimePickerView mTimePickerBack;

    @Autowired(name = RouterKey.INT, desc = "去程选择的仓位")
    int positionTo;

    boolean isChangePeople = false;

    private Map<String, Object> map;
    List<PickSelectEntity> airlineList;//航司数据

    @Autowired(name = RouterKey.DATA, desc = "航班搜索内容")
    FlightSearchEntity mEntity;

    @Autowired(name = RouterKey.DATA1, desc = "选择的去程航班信息")
    FlightInfoEntity mEntityChoose;

    private boolean mIsLoadMore = false;

    private static int STATE_PRICE = 0;
    private final static int STATE_PRICE_UP = 1;
    private final static int STATE_PRICE_DOWN = 2;
    private final static int STATE_PRICE_NONE = 0;

    private int requestCodeStart = 201;
    private int requestCodeArrive = 202;

    @Override
    protected int layoutId() {
        return R.layout.trip_activity_choose_single_flight;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(FlightSearchViewModel.class);
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        initView();
        mBinding.ivBack.setOnClickListener(view -> finish());
        mBinding.setOnClick(this);
        initWindow();
        initAdapter();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        getFlight();
        mViewModel.ldData.observe(this, list -> showProjectList(list, mIsLoadMore));
        mViewModel.getCodeList();
        mViewModel.ldDataAir.observe(this, list -> this.airlineList = list);
        mViewModel.ldToast.observe(this, message -> MToast.showToast(this, message));
    }

    private void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.trip_activity_choose_single_flight);
        mViewModel = new ViewModelProvider(this).get(FlightSearchViewModel.class);
        map = new HashMap<>();
        if (mEntity != null) {
            mBinding.setEntity(mEntity);

            if (mEntity.isSingle()) {
                mBinding.ivArrowDirection.setImageResource(R.mipmap.icon_arrow_right);
                mBinding.llChooseBack.setVisibility(View.GONE);
                mBinding.tvChooseFlightDate.setText(new StringBuilder().append("选择航班：").append(DateUtils.formatDate(mEntity.getStartDateStamp(), "MM月dd日"))
                        .append(" ").append("星期").append(mEntity.getStartWeek()));
                map.put("fromCity", mEntity.getStartCityNo());
                map.put("toCity", mEntity.getArriveCityNo());
                map.put("flightDate", mEntity.getStartDate());
                map.put("isSingleTicket", 1);
            } else {
                mBinding.ivArrowDirection.setImageResource(R.mipmap.icon_arrow_return);
                if (mEntity.isBack()) {
                    mBinding.tvChooseFlightDate.setText(new StringBuilder().append("选择返程：").append(DateUtils.formatDate(mEntity.getReturnDateStamp(), "MM月dd日"))
                            .append(" ").append("星期").append(mEntity.getBackWeek()));
                    map.put("fromCity", mEntity.getStartCityNo());
                    map.put("toCity", mEntity.getArriveCityNo());
                    map.put("flightDate", mEntity.getStartDate());
                    map.put("backDate", mEntity.getReturnDate());
                    map.put("isSingleTicket", 2);
                    map.put("flightToTime", mEntityChoose.getToDateTime());
                    mBinding.llChoosedTo.setVisibility(View.VISIBLE);
                    if (mEntityChoose != null) {
                        mBinding.tvToInfo.setText(new StringBuilder().append("已选去程：").append(DateUtils.formatDate(mEntity.getStartDateStamp(), "MM月dd日"))
                                .append(" ").append("星期").append(mEntity.getStartWeek()).append("\n")
                                .append(mEntityChoose.getFromAirportName()).append(mEntityChoose.getFromTerminal()).append(" → ")
                                .append(mEntityChoose.getToAirportName()).append(mEntityChoose.getToTerminal()).append("\n")
                                .append(mEntityChoose.getFromDateTime()).append("-").append(mEntityChoose.getToDateTime()));
                    }
                } else {
                    mBinding.tvChooseFlightDate.setText(new StringBuilder().append("选择去程：").append(DateUtils.formatDate(mEntity.getStartDateStamp(), "MM月dd日"))
                            .append(" ").append("星期").append(mEntity.getStartWeek()));
                    map.put("fromCity", mEntity.getStartCityNo());
                    map.put("toCity", mEntity.getArriveCityNo());
                    map.put("flightDate", mEntity.getStartDate());
                    map.put("backDate", mEntity.getReturnDate());
                    map.put("isSingleTicket", 1);
                    mBinding.llChooseBack.setVisibility(View.VISIBLE);
                    mBinding.tvBackInfo.setText(new StringBuilder().append("下一步选返程：").append(DateUtils.formatDate(mEntity.getReturnDateStamp(), "MM月dd日"))
                            .append(" ").append("星期").append(mEntity.getBackWeek()));
                }
            }
        }
    }

    private void initWindow() {
        flightPopWindow = new FlightPopWindow(this, mEntity);
        flightPopWindow.setOnClickCallBack(new FlightPopWindow.OnClickCallBack() {
            @Override
            public void chooseStartCity() {
                Intent intent = new Intent();
                intent.setClass(FlightSearchActivity.this, CitySelectionActivity.class);
                startActivityForResult(intent, requestCodeStart);
            }

            @Override
            public void chooseArriveCity() {
                Intent intent1 = new Intent();
                intent1.setClass(FlightSearchActivity.this, CitySelectionActivity.class);
                startActivityForResult(intent1, requestCodeArrive);
            }

            @Override
            public void chooseStartDate() {
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.YEAR, 1);//增加一年

                mTimePickerSrart = PickerHelper.with(FlightSearchActivity.this).getCommonTimeBuild((date, view) -> {
                    flightPopWindow.setStartDate(date);
                }).setOutSideColor(getResources().getColor(R.color.transparent))
                        .setLineSpacingMultiplier(2.0f)
                        .setRangDate(Calendar.getInstance(), cal)
                        .build();
                mTimePickerSrart.setTitleText("选择出发日期");
                if (mEntity.getStartDateStamp() != 0) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(mEntity.getStartDateStamp());
                    mTimePickerSrart.setDate(calendar);
                }
                mTimePickerSrart.show(mBinding.ctvContent);
            }

            @Override
            public void chooseReturnDate() {
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.YEAR, 1);//增加一年
                mTimePickerBack = PickerHelper.with(FlightSearchActivity.this).getCommonTimeBuild((date, view) -> {
                    flightPopWindow.setReturnDate(date);
                }).setOutSideColor(getResources().getColor(R.color.transparent))
                        .setLineSpacingMultiplier(2.0f)
                        .setRangDate(Calendar.getInstance(), cal)
                        .build();
                mTimePickerBack.setTitleText("选择返回日期");
                if (mEntity.getReturnDateStamp() != 0) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(mEntity.getReturnDateStamp());
                    mTimePickerBack.setDate(calendar);
                }
                mTimePickerBack.show(mBinding.ctvContent);
            }
        });
        flightPopWindow.setOnSearchCallBack(new FlightPopWindow.OnSearchCallBack() {
            @Override
            public void search(FlightSearchEntity entity) {
                map.clear();
                if (mEntity.isSingle()) {
                    mBinding.llPopGray.setVisibility(View.GONE);
                    mBinding.ivShowWindow.setImageResource(R.mipmap.icon_arrow_down);
                    mBinding.llPop.removeAllViews();
                    mBinding.setEntity(entity);
                    mBinding.tvChooseFlightDate.setText(new StringBuilder().append("选择航班：").append(DateUtils.formatDate(entity.getStartDateStamp(), "MM月dd日"))
                            .append(" ").append("星期").append(entity.getStartWeek()));
                    map.put("fromCity", entity.getStartCityNo());
                    map.put("toCity", entity.getArriveCityNo());
                    map.put("flightDate", entity.getStartDate());
                    mIsLoadMore = false;
                    getFlight();
                } else {
                    if (mEntity.isBack()) {
                        if (!entity.getStartCityNo().equals(mEntity.getStartCityNo()) || !entity.getArriveCityNo().equals(mEntity.getArriveCityNo())
                                || !entity.getStartDate().equals(mEntity.getStartDate()) || !entity.getReturnDate().equals(mEntity.getReturnDate())) {
                            finish();
                            EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_TRIP_RE_CHOOSE_TO));
                            entity.setSingle(false);
                            entity.setBack(false);
                            ARouter.getInstance().build(PathTrip.FlightSearchActivity).withSerializable(RouterKey.DATA, entity).navigation();
                        }
                    } else {
                        mBinding.llPopGray.setVisibility(View.GONE);
                        mBinding.ivShowWindow.setImageResource(R.mipmap.icon_arrow_down);
                        mBinding.llPop.removeAllViews();
                        mBinding.setEntity(entity);
                        mBinding.tvChooseFlightDate.setText(new StringBuilder().append("选择去程：").append(DateUtils.formatDate(entity.getStartDateStamp(), "MM月dd日"))
                                .append(" ").append("星期").append(entity.getStartWeek()));
                        mBinding.tvBackInfo.setText(new StringBuilder().append("下一步选返程：").append(DateUtils.formatDate(entity.getReturnDateStamp(), "MM月dd日"))
                                .append(" ").append("星期").append(entity.getBackWeek()));
                        map.put("fromCity", entity.getStartCityNo());
                        map.put("toCity", entity.getArriveCityNo());
                        map.put("flightDate", entity.getStartDate());
                        map.put("backDate", entity.getReturnDate());
                        mIsLoadMore = false;
                        getFlight();
                    }
                }
                mEntity.setStartCity(entity.getStartCity());
                mEntity.setStartCityNo(entity.getStartCityNo());
                mEntity.setArriveCity(entity.getArriveCity());
                mEntity.setArriveCityNo(entity.getArriveCityNo());
                mEntity.setStartDate(entity.getStartDate());
                mEntity.setStartDateStamp(entity.getStartDateStamp());
                mEntity.setReturnDate(entity.getReturnDate());
                mEntity.setReturnDateStamp(entity.getReturnDateStamp());
                mEntity.setStartWeek(entity.getStartWeek());
                mEntity.setBackWeek(entity.getBackWeek());

                mBinding.stvPeopleCount.contentSelect(false, false);
                isChangePeople = false;
                mBinding.stvPeopleCount.setText("乘客人数");
                if (peopleCountWindow != null) {
                    peopleCountWindow.setDefItem(-1);
                }
                setPriceState(STATE_PRICE_NONE);
                if (moreWindow != null) {
                    moreWindow.resetWindow();
                }
            }
        });

        moreWindow = new FlightMoreFilterPopWindow(this);
        moreWindow.setOnClickCallBack(new FlightMoreFilterPopWindow.OnClickCallBack() {
            @Override
            public void result(FlightLineSearchEntity entity) {
                if (entity != null) {
                    if (!TextUtils.isEmpty(entity.getFromTime())) {
                        map.put("fromTime", entity.getFromTime());
                    } else {
                        map.remove("fromTime");
                    }
                    if (entity.getCabinLevel() != null && entity.getCabinLevel().size() > 0) {
                        map.put("cabinLevel", entity.getCabinLevel());
                    } else {
                        map.remove("cabinLevel");
                    }
                    if (entity.getAirlineCode() != null && entity.getAirlineCode().size() > 0) {
                        map.put("airlineCode", entity.getAirlineCode());
                    } else {
                        map.remove("airlineCode");
                    }
                }
                mIsLoadMore = false;
                getFlight();
            }
        });
        moreWindow.setBgView(mBinding.allGrayLayout);

        peopleCountWindow = new IpPopWindow(this);
        peopleCountWindow.setDefItem(-1);
        peopleCountWindow.setOnResultClick((type, key2, key3) -> {
            isChangePeople = true;
            mBinding.stvPeopleCount.contentSelect(true, false);
            mBinding.stvPeopleCount.setText(((PickSelectEntity) type).getName());
            map.put("quantity", ((PickSelectEntity) type).getValue());

            mIsLoadMore = false;
            getFlight();

        });
        peopleCountWindow.setOnDismissListener(() -> {
            if (isChangePeople) {
                mBinding.stvPeopleCount.contentSelect(true, false);
            } else {
                mBinding.stvPeopleCount.contentSelect(false, false);
            }
        });
        peopleCountWindow.setBgView(mBinding.grayLayout);

        mBinding.rlPrice.setOnClickListener(view -> {
            if (STATE_PRICE == STATE_PRICE_NONE) {
                setPriceState(STATE_PRICE_UP);
                map.put("priceSort", "asc");
            } else if (STATE_PRICE == STATE_PRICE_UP) {
                setPriceState(STATE_PRICE_DOWN);
                map.put("priceSort", "desc");
            } else {
                setPriceState(STATE_PRICE_UP);
                map.put("priceSort", "asc");
            }

            mIsLoadMore = false;
            getFlight();
        });

        mViewModel.setPeopleCountData();
        mViewModel.ldDataPeopleCount.observe(this, list -> peopleCountWindow.setData(list));
    }

    private void getFlight() {
        DialogHelper.showProgressDialog(this, "请求中");
        mViewModel.checkFlight(map);
    }


    private void setPriceState(int state) {
        switch (state) {
            case STATE_PRICE_DOWN://降序
                STATE_PRICE = STATE_PRICE_DOWN;
                mBinding.rlPrice.setBackground(getResources().getDrawable(R.drawable.select_red_bg));
                mBinding.imgPriceUp.setImageResource(R.mipmap.icn_up_arrow_n);
                mBinding.imgPriceDown.setImageResource(R.mipmap.icon_down_red);
                mBinding.tvPriceContent.setTextColor(getResources().getColor(R.color.color_EF4033_link));
                break;
            case STATE_PRICE_UP://升序
                STATE_PRICE = STATE_PRICE_UP;
                mBinding.rlPrice.setBackground(getResources().getDrawable(R.drawable.select_red_bg));
                mBinding.imgPriceUp.setImageResource(R.mipmap.icon_up_red);
                mBinding.imgPriceDown.setImageResource(R.mipmap.ic_down_arrow_n);
                mBinding.tvPriceContent.setTextColor(getResources().getColor(R.color.color_EF4033_link));
                break;
            case STATE_PRICE_NONE://未选择
                STATE_PRICE = STATE_PRICE_NONE;
                mBinding.rlPrice.setBackground(getResources().getDrawable(R.drawable.search_bg));
                mBinding.imgPriceUp.setImageResource(R.mipmap.icn_up_arrow_n);
                mBinding.imgPriceDown.setImageResource(R.mipmap.ic_down_arrow_n);
                mBinding.tvPriceContent.setTextColor(getResources().getColor(R.color.FF333333));
                break;
        }
    }

    private void initAdapter() {
        mBinding.rvFlight.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rvFlight.setLoadingMoreEnabled(false);
        mBinding.rvFlight.setPullRefreshEnabled(false);
        mAdapter = new FlightInfoAdapter(this, null);
        mAdapter.setOnItemClick(new AdapterOnItemClick<FlightInfoEntity>() {
            @Override
            public void onItemClick(FlightInfoEntity flightInfoEntity, int position) {
                ARouter.getInstance().build(PathTrip.FlightBookActivity).withSerializable(RouterKey.DATA1, mEntity).withSerializable(RouterKey.DATA, flightInfoEntity)
                        .withSerializable(RouterKey.DATA2, mEntityChoose).withInt(RouterKey.INT, positionTo).navigation();
            }
        });
        mBinding.rvFlight.setAdapter(mAdapter);
        mBinding.rvFlight.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mIsLoadMore = false;

            }

            @Override
            public void onLoadMore() {
                mIsLoadMore = true;

            }
        });
    }

    /**
     * 数据
     *
     * @param list
     * @param isLoadMore
     */
    public void showProjectList(List<FlightInfoEntity> list, boolean isLoadMore) {
        DialogHelper.dismissProgressDialog();
        mBinding.rvFlight.refreshComplete();
        mBinding.rvFlight.loadMoreComplete();
        if (isLoadMore) {
            if (null != list && list.size() > 0) {
                mBinding.rvFlight.setNoMore(false);
                mAdapter.addDatas(list);
            } else {
                mBinding.rvFlight.setNoMore(true);
            }
            mBinding.rvFlight.setVisibility(View.VISIBLE);
        } else {
            if (null != list && list.size() > 0) {
                mBinding.rvFlight.setVisibility(View.VISIBLE);
                mBinding.errorView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
            } else {
                mAdapter.setDatas(null);
                mBinding.rvFlight.setVisibility(View.GONE);
                mBinding.errorView.setVisibility(View.VISIBLE);
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if (id == R.id.iv_show_window) {
            if (mBinding.llPopGray.getVisibility() == View.GONE) {
                mBinding.llPopGray.setVisibility(View.VISIBLE);
                mBinding.ivShowWindow.setImageResource(R.mipmap.icon_arrow_up);
                mBinding.llPop.removeAllViews();
                mBinding.llPop.addView(flightPopWindow);
            }
        } else if (id == R.id.tv_more_choose) {//更多
            if (airlineList != null && airlineList.size() > 0) {
                moreWindow.setCompanyDatas(airlineList);
            }
            moreWindow.showPopwindowRight(mBinding.rlChoose);
        } else if (id == R.id.stv_people_count) {//乘客人数
            if (peopleCountWindow != null) {
                mBinding.stvPeopleCount.contentSelect(false, true);
                peopleCountWindow.showPopwindow(mBinding.rlChoose, 0, 0);
            }
        } else if (id == R.id.ll_pop_gray) {
            mBinding.llPopGray.setVisibility(View.GONE);
            mBinding.ivShowWindow.setImageResource(R.mipmap.icon_arrow_down);
            mBinding.llPop.removeAllViews();
        } else if (id == R.id.tv_reChoose_to) {//重选去程
            finish();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && resultCode == 200) {
            AirportCityEntity aMapAddressEntity = (AirportCityEntity) data.getExtras().get(RouterKey.DATA);
            if (requestCode == requestCodeStart) {
                if (flightPopWindow != null) {
                    flightPopWindow.setStartCity(aMapAddressEntity);
                }
            } else if (requestCode == requestCodeArrive) {
                if (flightPopWindow != null) {
                    flightPopWindow.setArriveCity(aMapAddressEntity);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解绑eventBus
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MainEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_TRIP_RE_CHOOSE_TO) {
            finish();
        }
    }

}
